<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/17 0017
 * Time: 0:02
 */

namespace app\Lib\Model\User;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\User\AddUserBase as Api;
use app\Lib\Model\DbModel\AdminUserPriAuth;
use app\Lib\Model\DbModel\UserBase;

class AddUserBase extends OperationUserBase implements Api
{
    /**
     * 新增后台用户
     * @return bool
     * @throws BlException
     */
    public function addAdminAccount(){
        $this->checkAccount();
        $data = $this->neatenData();
        $table = $this->getTable();
        $password = 123456;//初始密码;
        $data[$table->_password] = md5(md5($this->prefix.$password).$this->prefix);
        $data[$table->_reg_ip] = $this->regIp;
        $data[$table->_reg_time] = time();
        $data[$table->_account_status] = 1;
        $validate = $this->getValidate();
        if(!$validate->scene('checkAdminAddDataDb')->check($data)){
            throw new BlException($validate->getError());
        }
        $result = $table->insert($data,false,true);
        if(!$result){
            throw new BlException('添加新用户失败');
        }
        $user = new User($result);
        $userBingRole = (new UserBindingRole($user));
        $userBingRole->setOpUserObj($this->opUser)->setRoleObj($this->role)->run();
        $user->delUserCache();
        if($this->auth){
            $model = new AdminUserPriAuth();
            foreach ($this->auth as $k=>$v){
                $newData[$k]=[
                    $model->_create_uid=>$this->opUser->getUid(),
                    $model->_create_time=>time(),
                    $model->_menu_id=>$v,
                    $model->_uid=>$user->getUid(),
                    $model->_status=>1,
                ];
            }
            $result = $model->insertAll($newData);
            if(!$result){
                throw new BlException('授权失败');
            }
        }
        return true ;
    }

    /**
     * @return bool
     * @throws BlException
     */
    public function addWebAccount(){
        $table = $this->getTable();
        $data = $this->neatenData();
        $data['account']=$this->mobilephone;
        $data[$table->_reg_ip] = $this->regIp;
        $data[$table->_reg_time] = time();
        $data[$table->_account_status] = 1;
        $validate = $this->getValidate();
        if(!$validate->scene('checkWebAccount')->check($data)){
            throw new BlException($validate->getError());
        }
        $result = $table->where([$table->_weixin=>$this->weixin])->value('id');
        if($result){
            return true;
        }
        $result = $table->insert($data,false,true);
        if(!$result){
            throw new BlException('添加新用户失败');
        }
        return true;
    }


    private function checkAccount(){
        $result =  UserBase::getUid($this->account);
        if($result){
            throw new BlException('账号已存在请重新填写账号');
        }
        return true;
    }
}